//格式化时间
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 
function formatSubscribeTime(cellValue, options, rowObject) {
	var dateStr = "";
	if(cellValue){
		var crtTime = new Date(cellValue);
		dateStr = dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);
	}
    return dateStr;
}
//加载字典
function dictJudge(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.options.sex;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}

//查看材料
function showPhotos(id){
    if(id == null){
        return ;
    }
    vm.title = '图片';

    var domain = "http://20.0.51.77:8082/";
    var hostname = location.hostname;
    var port = location.port;

    if(hostname == "20.0.51.77" && port == "8080"){
        //视频专网
        domain = "http://20.0.51.77:8082/";
    }else if(hostname == "10.55.97.153" && port == "38080"){
        //公安内网
        domain = "http://10.55.97.153:28082";
    }else if(hostname == "222.174.70.56" && port == "33110"){
        //外网
        domain = "http://222.174.70.56:18082";
    }else if(hostname == "127.0.0.1" && port == "8080"){
        domain = "http://127.0.0.1:8082";
    }

    $.get(baseURL + "cgs/cgsreconsider/info/"+id, function(r){
        vm.cgsReconsider = r.cgsReconsider;

        $("#travelLicense").attr("src",domain + vm.cgsReconsider.travelLicense);
        $("#travelLicenseA").attr("href",domain + vm.cgsReconsider.travelLicense);
        $("#materialOne").attr("src",domain + vm.cgsReconsider.materialOne);
        $("#materialOneA").attr("href",domain + vm.cgsReconsider.materialOne);

        if(vm.cgsReconsider.materialTwo = "" || vm.cgsReconsider.materialTwo == null){
            document.getElementById('materialTwo').removeAttribute("src");
            document.getElementById('materialTwoA').removeAttribute("href");
        }
    });
    $('#showPhotosModal').modal('show');

}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'cgs/cgsreconsider/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true , hidden: true},
			{ label: '用户id', name: 'applyUserId', index: 'apply_user_id', width: 80 },
			{ label: '用户姓名', name: 'userName', index: 'user_name', width: 80 }, 			
			{ label: '身份证号', name: 'idCardNum', index: 'id_card_num', width: 80 }, 			
			{ label: '车牌号', name: 'vehicleNum', index: 'vehicle_num', width: 80 },
			// { label: '身份证正面照片', name: 'scanUrlZ', index: 'scan_url_z', width: 80 },
			// { label: '身份证反面照片', name: 'scanUrlF', index: 'scan_url_f', width: 80 },
			{ label: '违法时间', name: 'illegalTime', index: 'illegal_time', width: 80 },
			{ label: '道路类型01高速公路、02非高速公路', name: 'roadType', index: 'road_type', width: 80 },
			{ label: '复议内容', name: 'content', index: 'content', width: 80 },
			{ label: '状态0已提交1复议成功2复议失败', name: 'status', index: 'status', width: 80 }, 			
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80 }, 			
			{ label: '查看材料', name: '', index: '', width: 80,
                formatter: function (cellvalue, option, rowObject) {
                    return '&nbsp;&nbsp;<button class="btn btn-info btn-xs" type="button" onclick=showPhotos(\"' + rowObject.id + '\")>查看材料</button>';
                }
			}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        multiboxonly: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    //初始化日期范围组件
    $('#datepicker_range input').datepicker({
        language: 'zh-CN',//显示中文
        startView: 0, //选择器开始界面 0：天（默认 1：月2：年3：十年 4：世纪
        minViewMode: 0,//最小选择精度 0：天（最小默认）
        maxViewMode: 2, //最大选择精度 4：世纪（最大默认）
        format: 'yyyy-mm-dd',//显示格式
        minView: "day",//设置只显示到月份
        // initialDate: new Date(),
        autoclose: true,//选中自动关闭
        // todayBtn: true//显示今日按钮
        clearBtn: true //清除按钮
        //todayHighlight: true //今日高亮
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            userName:'',
            mobile:'',
            status:''
        },
		showList: true,
		title: null,
		cgsReconsider: {},

        statusObject:{} ,//办理状态集合

        statusUpdate:{
            id:'',
            status:''
        }

    },
    mounted:function(){
        this.$nextTick(function(){ this.initSysDict()});
    },
	methods: {
        initSysDict:function() {
            $.get(baseURL + "sys/dict/select/policePostStatus", function (r) {
                if (r.code === 0) {
                    vm.statusObject = r.dict;
                } else {
                    console.log(r.msg);
                }
            });
        },
        reset: function(){
            vm.q.businessName = '';
            vm.q.userName = '';
            vm.q.mobile = '';
            vm.q.status = '';
            $("#datepicker_start").val('');
            $("#datepicker_end").val('');

        },
		query: function () {
			vm.reload();
		},
		detail: function(){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
			vm.title = "办理详情";
            vm.getInfo(id);
            $('#detailModal').modal('show');

        },
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        checkOK: function(status){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.getInfo(id);
            console.log(vm.cgsReconsider);

            if (vm.cgsReconsider.status != "0") {
				alert("该业务已办理，无需重复办理");
				return;
			}
			vm.statusUpdate.id = id;
            vm.statusUpdate.status = status;
			console.log(vm.statusUpdate);
			vm.cgsReconsider.status = '1';
            confirm('确认要审核成功改信息么？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "cgs/cgsreconsider/update/"+id,
                    contentType: "application/json",
                    data: JSON.stringify(vm.statusUpdate),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });

        },
		saveOrUpdate: function (event) {
			var url = vm.cgsReconsider.id == null ? "cgs/cgsreconsider/save" : "cgs/cgsreconsider/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.cgsReconsider),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "cgs/cgsreconsider/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "cgs/cgsreconsider/info/"+id, function(r){
                vm.cgsReconsider = r.cgsReconsider;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'userName': vm.q.userName,
                    'mobile': vm.q.mobile,
                    'status': vm.q.status,
                    'startTime':$("#datepicker_start").val(),
                    'endTime':$("#datepicker_end").val()
                },
                page:page
            }).trigger("reloadGrid");
		}
	}
});